import 'dart:async';

import 'package:casdon/app/config/env/env_config.dart';
import 'package:casdon/app_providers.dart';
import 'package:casdon/common/service/service_manager.dart';
import 'package:casdon/modules/home/application/notification/tuya_auth_notifier.dart';
import 'package:casdon/modules/home/providers/home_provider.dart';
import 'package:casdon/modules/home/services/splash_cache_service.dart';
import 'package:casdon/modules/me/application/notification/app_update_info_notifier.dart';
import 'package:casdon/modules/me/application/notification/oss_sts_notifier.dart';
import 'package:casdon/modules/recipe/domain/usecase/miffy_product_list_usecase.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

class AppInitializer {
  final EnvConfig environment;

  // 构造方法的简写，常用于final属性的初始化
  AppInitializer(this.environment);

  Future<void> init() async {
    // 初始化所有第三方服务
    await ServiceManager().initServices();
    unawaited(_loadNonCriticalProviders());
  }

  // 加载非关键的provider
  Future<void> _loadNonCriticalProviders() async {
    final isReady = await getProvider(canUseAuthInfoProvider.future);
    if (isReady == false) return;
    getProvider(appUpdateInfoProvider.future);
    getProvider(ossTokenProvider);
    getProvider(miffyRecipeProductListProvider);
    final splashFuture = getProvider(splashListProvider.future);
    final popupFuture = getProvider(popupListProvider.future);

    final splashList = await splashFuture;
    final splashCache = getProvider(splashCacheServiceProvider);
    unawaited(splashCache.cacheSplashList(splashList));

    await popupFuture;
  }
}

// 等待涂鸦登陆成功，
final canUseAuthInfoProvider = FutureProvider<bool>((ref) async {
  final completer = Completer<bool>();
  ref.keepAlive();

  final sub = ref.listen<bool>(tuyaLoginStateProvider, (previous, next) {
    if (next) {
      if (!completer.isCompleted) completer.complete(true);
    }
  });

  // 如果已经登录，直接返回
  final current = ref.read(tuyaLoginStateProvider);
  if (current) {
    completer.complete(true);
  }

  // 等待登录完成
  final result = await completer.future;

  // 监听完成后取消订阅
  sub.close();

  return result;
});
